package org.wisdom.ab.apis.assembler;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.wisdom.ab.domain.department.entity.AbDepartment;
import org.wisdom.ab.domain.department.repository.DepartmentRepository;
import org.wisdom.ab.dto.DepartmentDto;
import org.wisdom.exception.BusinessException;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 部门组装器
 *
 * @author 张智研
 * @date 2022/05/23 09:53
 **/
@AllArgsConstructor
@Component
public class DepartmentAssembler {

    private final DepartmentRepository departmentRepository;

    /**
     * 部门dto转换为实体
     *
     * @author 张智研
     * @date 2022/05/23 10:21
     * @param departmentDto
     *            部门
     * @return org.wisdom.ab.domain.entity.AbDepartment
     */
    public AbDepartment departmentDtoToEntity(DepartmentDto departmentDto) {
        String parentDeptId = departmentDto.getParentId();
        String parentDeptIdPath = "/";
        String rootId = "0";
        if (!rootId.equals(parentDeptId)) {
            Optional<AbDepartment> departmentOptional = this.departmentRepository.findById(parentDeptId);
            if (departmentOptional.isPresent()) {
                AbDepartment parentDepartment = departmentOptional.get();
                parentDeptIdPath = parentDepartment.getDeptIdPath().concat(parentDepartment.getId());
            } else {
                throw new BusinessException("上级部门{" + parentDeptId + "}不存在!");
            }
        }else {
            parentDeptIdPath = parentDeptIdPath.concat(rootId);
        }
        departmentDto.setDeptIdPath(parentDeptIdPath.concat("/"));
        return BeanUtil.copyProperties(departmentDto, AbDepartment.class);
    }

    /**
     * 部门实体转换为dto
     *
     * @author 张智研
     * @date 2022/05/23 10:24
     * @param department
     *            部门
     * @return org.wisdom.ab.dto.DepartmentDto
     */
    public DepartmentDto departmentEntityToDto(AbDepartment department) {
        return BeanUtil.copyProperties(department, DepartmentDto.class);
    }

    /**
     * 部门实体列表转换为dto列表
     *
     * @author 张智研
     * @date 2022/05/23 10:25
     * @param departmentList
     *            部门列表
     * @return java.util.List<org.wisdom.ab.dto.DepartmentDto>
     */
    public List<DepartmentDto> departmentEntityToDto(List<AbDepartment> departmentList) {
        return departmentList.stream().map(this::departmentEntityToDto).collect(Collectors.toList());
    }
}
